#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
批量修复Django兼容性问题的脚本
"""
import os
import re
import glob
import sys

def fix_file(file_path):
    """修复单个文件中的Django兼容性问题"""
    try:
        # 跳过不需要修复的文件
        if any(skip in file_path for skip in ['__pycache__', '.pyc', '.git', 'compatibility']):
            return False
            
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
        
        original_content = content
        
        # 1. 修复 ugettext_lazy 导入
        content = re.sub(
            r'from django\.utils\.translation import ugettext_lazy as _',
            'from django.utils.translation import gettext_lazy as _',
            content
        )
        
        # 2. 修复 ugettext_lazy 导入（不带 as _）
        content = re.sub(
            r'from django\.utils\.translation import ([^,]*,\s*)?ugettext_lazy',
            r'from django.utils.translation import \1gettext_lazy',
            content
        )
        
        # 3. 修复 ugettext 导入
        content = re.sub(
            r'from django\.utils\.translation import ugettext,',
            'from django.utils.translation import gettext as ugettext,',
            content
        )
        
        content = re.sub(
            r'from django\.utils\.translation import ugettext\s*$',
            'from django.utils.translation import gettext as ugettext',
            content,
            flags=re.MULTILINE
        )
        
        # 4. 修复 django.core.urlresolvers 导入
        content = re.sub(
            r'from django\.core\.urlresolvers import',
            'from django.urls import',
            content
        )
        
        # 5. 修复 django.contrib.contenttypes.generic 导入
        content = re.sub(
            r'from django\.contrib\.contenttypes\.generic import GenericRelation',
            'from django.contrib.contenttypes.fields import GenericRelation',
            content
        )
        
        content = re.sub(
            r'from django\.contrib\.contenttypes\.generic import GenericForeignKey',
            'from django.contrib.contenttypes.fields import GenericForeignKey',
            content
        )
        
        content = re.sub(
            r'from django\.contrib\.contenttypes import generic',
            'from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation',
            content
        )
        
        # 6. 修复 generic.GenericForeignKey 使用
        content = re.sub(
            r'generic\.GenericForeignKey',
            'GenericForeignKey',
            content
        )
        
        # 7. 修复 generic.GenericRelation 使用
        content = re.sub(
            r'generic\.GenericRelation',
            'GenericRelation',
            content
        )
        
        # 8. 修复 ungettext 导入
        content = re.sub(
            r'from django\.utils\.translation import ([^,]*,\s*)?ungettext',
            r'from django.utils.translation import \1ngettext as ungettext',
            content
        )
        
        # 9. 修复混合导入语句
        content = re.sub(
            r'from django\.utils\.translation import get_language_from_request, ugettext_lazy as _',
            'from django.utils.translation import get_language_from_request, gettext_lazy as _',
            content
        )
        
        content = re.sub(
            r'from django\.utils\.translation import ugettext_lazy as _, ugettext',
            'from django.utils.translation import gettext_lazy as _, gettext as ugettext',
            content
        )
        
        content = re.sub(
            r'from django\.utils\.translation import ugettext, ugettext_lazy as _',
            'from django.utils.translation import gettext as ugettext, gettext_lazy as _',
            content
        )
        
        # 10. 修复 ugettext_lazy 变量声明
        content = re.sub(
            r'ugettext_lazy\s*=\s*',
            'gettext_lazy = ',
            content
        )
        
        # 11. 修复 Django 1.9+ 的 contrib.contenttypes.generic 问题
        # 为使用 generic 的文件添加兼容性代码
        if 'generic.' in content and 'from django.contrib.contenttypes import generic' not in content:
            generic_compat = """
# Django 1.9+ 兼容性
try:
    from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
    class generic:
        GenericForeignKey = GenericForeignKey
        GenericRelation = GenericRelation
except ImportError:
    from django.contrib.contenttypes import generic
"""
            # 在import部分之后添加兼容性代码
            import_pattern = r'(from django\.contrib\.contenttypes\.fields import[^\n]*\n)'
            if re.search(import_pattern, content):
                content = re.sub(import_pattern, r'\1' + generic_compat, content, count=1)
        
        # 只有在内容发生变化时才写入文件
        if content != original_content:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"✓ 修复完成: {file_path}")
            return True
        else:
            return False
            
    except Exception as e:
        print(f"✗ 修复失败 {file_path}: {e}")
        return False

def main():
    """主函数"""
    base_dir = os.path.dirname(os.path.abspath(__file__))
    
    print("开始批量修复Django兼容性问题...")
    print("=" * 50)
    
    # 获取所有Python文件
    python_files = []
    for root, dirs, files in os.walk(base_dir):
        # 跳过某些目录
        dirs[:] = [d for d in dirs if d not in ['__pycache__', '.git', 'static', 'media']]
        
        for file in files:
            if file.endswith('.py'):
                python_files.append(os.path.join(root, file))
    
    print(f"找到 {len(python_files)} 个Python文件")
    
    # 修复文件
    fixed_count = 0
    failed_count = 0
    
    for file_path in python_files:
        try:
            if fix_file(file_path):
                fixed_count += 1
        except Exception as e:
            print(f"✗ 处理文件失败 {file_path}: {e}")
            failed_count += 1
    
    print("=" * 50)
    print(f"修复完成！")
    print(f"✓ 成功修复: {fixed_count} 个文件")
    print(f"✗ 失败: {failed_count} 个文件")
    print(f"总计处理: {len(python_files)} 个文件")
    
    # 特别处理一些关键文件
    print("\n处理关键文件...")
    key_files = [
        'apps/warehouse/models.py',
        'apps/material/models.py', 
        'apps/device/models.py',
        'apps/maintenance/models.py',
        'apps/quality/models.py',
        'apps/productcatalog/models.py',
        'apps/person/models.py',
        'apps/customer/models.py',
    ]
    
    for key_file in key_files:
        file_path = os.path.join(base_dir, key_file)
        if os.path.exists(file_path):
            try:
                if fix_file(file_path):
                    print(f"✓ 关键文件修复: {key_file}")
                else:
                    print(f"- 关键文件无需修复: {key_file}")
            except Exception as e:
                print(f"✗ 关键文件修复失败 {key_file}: {e}")
        else:
            print(f"- 关键文件不存在: {key_file}")

if __name__ == '__main__':
    main() 